package com.nsi.o2o.util;

import com.nsi.o2o.dto.ImageHolder;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * @author: Luo Zhen
 * @date: 2018/9/6 22:00
 * @description: 图片工具类
 */
public class ImageUtil {

    private static Logger logger = LoggerFactory.getLogger(ImageUtil.class);

    private static String basePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();

    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

    private static final Random r = new Random();

    public static String generateThumbnail(ImageHolder thumbnail, String targetAddr) {
        String readFileName = getRandomFileName();
        String extension = getFileExtension(thumbnail.getImageName());
        makeDirPath(targetAddr);
        String relativeAddr = targetAddr + readFileName + extension;
        logger.debug("current relativeAddr is:" + relativeAddr);
        File desk = new File(PathUtil.getImageBasePath() + relativeAddr);
        logger.debug("current complete addr is:" + PathUtil.getImageBasePath() + relativeAddr);
        try {
            Thumbnails.of(thumbnail.getImage())
                    //如果要指明尺寸
                    .size(1000, 1000)
                    //如果要加水印  请指明Position  图片位置  清晰度
                    //.watermark(Positions.BOTTOM_CENTER, ImageIO.read(thumbnail), 0.5f)
                    .outputQuality(0.8f)
                    .toFile(desk);

        } catch (IOException e) {
            logger.error(e.toString());
            throw new RuntimeException("创建图片失败:" + e.getMessage());
        }
        return relativeAddr;
    }

    /**
     * 创建目标路径锁涉及到的目录，即
     *
     * @param targetAddr
     */
    private static void makeDirPath(String targetAddr) {
        String readFileParentPath = PathUtil.getImageBasePath() + targetAddr;
        File dirPath = new File(readFileParentPath);
        if (!dirPath.exists()) {
            dirPath.mkdirs();
        }
    }

    /**
     * 获取文件扩展名
     *
     * @param fileName
     * @return
     */
    private static String getFileExtension(String fileName) {
        return fileName.substring(fileName.lastIndexOf("."));
    }

    /**
     * 生成随机文件名，当前年月日小时分钟秒，5伪随机数
     *
     * @return
     */
    public static String getRandomFileName() {
        int ranNum = r.nextInt(89999) + 10000;
        String notTime = sdf.format(new Date());
        return notTime + ranNum;
    }

    /**
     * sotrePath 是文件还是目录的路径，
     * 如果是文件路径则删除该文件
     * 如果是目录路径则删除该目录下的所有文件
     *
     * @param storePath
     */
    public static void deleteFileOrPath(String storePath) {
        File fileOrPath = new File(PathUtil.getImageBasePath() + storePath);
        if (fileOrPath.exists()) {
            if (fileOrPath.isDirectory()) {
                File file[] = fileOrPath.listFiles();
                for (int i = 0; i < file.length; i++) {
                    file[i].delete();
                }
            }
            fileOrPath.delete();
        }
    }

    /**
     * 返回描述产品多图(指定尺寸)
     *
     * @param imageHolder
     * @param dest
     * @return
     */
    public static String generateNormalImg(ImageHolder imageHolder, String dest) {
        String readFileName = getRandomFileName();
        String extension = getFileExtension(imageHolder.getImageName());
        makeDirPath(dest);
        String relativeAddr = dest + readFileName + extension;
        logger.debug("current relativeAddr is:" + relativeAddr);
        File desk = new File(PathUtil.getImageBasePath() + relativeAddr);
        logger.debug("current complete addr is:" + PathUtil.getImageBasePath() + relativeAddr);
        try {
            Thumbnails.of(imageHolder.getImage())
                    //如果要指明尺寸
                    .size(337, 640)
                    //如果要加水印  请指明Position  图片位置  清晰度
                    //.watermark(Positions.BOTTOM_CENTER, ImageIO.read(thumbnail), 0.5f)
                    .outputQuality(0.8f)
                    .toFile(desk);

        } catch (IOException e) {
            logger.error(e.toString());
            throw new RuntimeException("创建图片失败:" + e.getMessage());
        }
        return relativeAddr;
    }


}
